package com.github.postsanf.yinian.huanxin.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;
import android.widget.Toast;

import com.github.postsanf.yinian.BaseApplication;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.bean.Ext;
import com.github.postsanf.yinian.bean.YNHistory;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.entity.YNHistoryMessageResponse;
import com.github.postsanf.yinian.huanxin.runtimepermissions.PermissionsManager;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.StringUtils;
import com.google.gson.Gson;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.util.EasyUtils;
import com.litesuits.http.HttpConfig;
import com.litesuits.http.LiteHttp;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import easeui.ui.EaseChatHistoryFragment;

/**
 * chat activity，EaseChatFragment was used {@link #EaseChatFragment}
 */
public class ChatHistoryActivity extends BaseActivity {
    public static ChatHistoryActivity activityInstance;
    private EaseChatHistoryFragment chathistoryFragment;
    String toChatUsername;
    private BaseApplication application;

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.em_activity_chathistory);
        application = (BaseApplication) getApplication();
        activityInstance = this;
        //get user id or group id
        toChatUsername = getIntent().getExtras().getString("userId");
        //use EaseChatFratFragment
        initHistoryMessage(toChatUsername, "initialize");
    }

    private void initHistoryMessage(final String gimid, String type) {
        Log.i("xjs", "gimid==>" + gimid);
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put("gimid", gimid);
        mParam.put("type", type);
        StringRequest req = new StringRequest(getString(R.string.CHAT_HISTORY_MESSAGE))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNHistoryMessageResponse historyMessageResponse = new Gson().fromJson(s, YNHistoryMessageResponse.class);
                        if (historyMessageResponse != null && ReqUtils.isSuccess(historyMessageResponse.getCode())) {
                            List<YNHistory> data = historyMessageResponse.getData();
                            List<EMMessage> emMessageList = new ArrayList<EMMessage>();
                            if (data.size() == 0)
                                return;
                            for (int i = 0; i < data.size(); i++) {
                                YNHistory ynHistory = data.get(i);
                                EMMessage emMessage = null;
                                String Msg = ynHistory.getPayload().getBodies().get(0).getMsg();
                                String sendtype = ynHistory.getPayload().getBodies().get(0).getType();
                                if (!StringUtils.isEmpty(sendtype)) {
                                    if (sendtype.equals("txt")) {
                                        if (!StringUtils.isEmpty(Msg)) {
                                            emMessage = EMMessage.createTxtSendMessage(Msg, gimid);
                                        } else {
                                            emMessage = EMMessage.createTxtSendMessage(" ", gimid);
                                        }
                                        String extStr = ynHistory.getPayload().getExt();
                                        if (!StringUtils.isEmpty(extStr) && !extStr.equals("{}")) {
                                            Ext ext = new Gson().fromJson(extStr.replaceAll("\\\\", ""), Ext.class);
                                            if (ext != null) {
                                                if (ext.getImg() != null && !StringUtils.isEmpty(ext.getImg())) {
                                                    emMessage.setAttribute("img", ext.getImg());
                                                }
                                                if (ext.getAccountName() != null && !StringUtils.isEmpty(ext.getAccountName())) {
                                                    emMessage.setAttribute("accountName", ext.getAccountName());
                                                }
                                                if (ext.getFristpic() != null && !StringUtils.isEmpty(ext.getFristpic())) {
                                                    emMessage.setAttribute("fristpic", ext.getFristpic());
                                                }
                                                if (ext.getEventId() != null && !StringUtils.isEmpty(ext.getEventId())) {
                                                    emMessage.setAttribute("eventId", ext.getEventId());
                                                }
                                                if (ext.getType() != null && !StringUtils.isEmpty(ext.getType())) {
                                                    emMessage.setAttribute("type", String.valueOf(ext.getType()));
                                                }
                                            }
                                        }
                                        emMessage.setChatType(EMMessage.ChatType.GroupChat);
                                        emMessage.setDirection(ynHistory.getFrom().equals(String.valueOf(application.getCurID())) ? EMMessage.Direct.SEND : EMMessage.Direct.RECEIVE);
                                        emMessage.setStatus(EMMessage.Status.SUCCESS);
                                        emMessage.setMsgTime(ynHistory.getTimestamp());
                                        emMessage.setFrom(ynHistory.getFrom());
                                        emMessage.setTo(ynHistory.getTo());
                                        emMessageList.add(emMessage);
                                    }
                                }
                            }
                            application.setEmHistoryList(data);
                            application.setEmMessageList(emMessageList);
                            chathistoryFragment = new ChatHistoryFragment();
                            chathistoryFragment.setArguments(getIntent().getExtras());
                            getSupportFragmentManager().beginTransaction().add(R.id.container, chathistoryFragment).commit();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        Toast.makeText(ChatHistoryActivity.this, CommonConstants.YN_NET_LINK, Toast.LENGTH_SHORT).show();
                    }
                });
        LiteHttp.newApacheHttpClient(new HttpConfig(ChatHistoryActivity.this)).executeAsync(req);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        activityInstance = null;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        // make sure only one chat activity is opened
        String username = intent.getStringExtra("userId");
        if (toChatUsername.equals(username))
            super.onNewIntent(intent);
        else {
            finish();
            startActivity(intent);
        }

    }

    @Override
    public void onBackPressed() {
        if (chathistoryFragment != null) {
            chathistoryFragment.onBackPressed();
        } else {
            finish();
        }
        if (EasyUtils.isSingleActivity(this)) {
            Intent intent = new Intent(this, ChatMemberActivity.class);
            startActivity(intent);
        }
    }

    public String getToChatUsername() {
        return toChatUsername;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        PermissionsManager.getInstance().notifyPermissionsChange(permissions, grantResults);
    }
}
